<?php
define("TOKEN", "pc0524");
$wechatObj = new wechatCallback();

if (isset($_GET['echostr'])) {
    $wechatObj->valid();
}else{
    //global $msgcontent;
    $msgcontent = $wechatObj->get_msgcontent();
    
    switch ($msgcontent->MsgType) {
        case 'text':
            $wechatObj->cheak_step($msgcontent);
            break;
        case 'music':
            $wechatObj->music_response($msgcontent);
            break;
        case 'video':
            $wechatObj->video_response($msgcontent);
            break;
        case 'image':
            $wechatObj->img_response($msgcontent);
            break;
        case 'voice':
            $wechatObj->voice_response($msgcontent);
            break;
        case 'location':
            $wechatObj->location_response($msgcontent);
            break;
        case 'event':
            if ($msgcontent->Event=="subscribe") {
                $wechatObj->first_response($msgcontent);
            }
            break;
        case 'shortvideo':
            $wechatObj->shortvideo_response($msgcontent);
            break;
        default:
            $wechatObj->unknown_response($msgcontent);
            break;
        }
    }
/*====================================================================================================================*\
                                        class封包,包括所使用的所有函数函数
                                            创建时间：2017年1月18日
\*====================================================================================================================*/
class wechatCallback
{
    
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            header('content-type:text');
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];

        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );

        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
/*  分析用户发送消息基本信息  */
    public function get_msgcontent()
    {       
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        if (!empty($postStr))
        {       
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);//解析XML，存入对象中
            return $postObj;
        }else{
            echo "";
            exit;
        }
    } 
/*  定义纯文本、图片、语音、音乐、视频回复方法  *//*  定义纯文本、图片、语音、音乐、视频回复方法  */
//如需回复纯文本信息，则只需要调用send_msg函数即可
    public function send_text($resultmsg)
    {
        $time = time();
        $msgType = "text";
        $textTpl = "<xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[%s]]></MsgType>
                    <Content><![CDATA[%s]]></Content>
                    <FuncFlag>0</FuncFlag>
                    </xml>"; 
        global $msgcontent;//使用glob访问class外部变量
        $fromUsername= $msgcontent->FromUserName;
        $toUsername=$msgcontent->ToUserName;
        $contentStr=$resultmsg;
        $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
        echo $resultStr;
    }
    /*多图文消息*/
    public function send_articles($newsArray)
    {
        if(!is_array($newsArray)){
            return;
        }
        
        $itemTpl = "<item>
                    <Title><![CDATA[%s]]></Title>
                    <Description><![CDATA[%s]]></Description>
                    <PicUrl><![CDATA[%s]]></PicUrl>
                    <Url><![CDATA[%s]]></Url>
                    </item>";
        $item_str = "";
        if (count($newsArray)>8){   //防止图文过多（>10）导致错误
            $Array_count=8;
        }else{
            $Array_count=count($newsArray);
        }
        
        foreach ($newsArray as $item){
            $count=$count+1;
            if ($count>8){
                break;
            }
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = " <xml>
                    <ToUserName><![CDATA[%s]]></ToUserName>
                    <FromUserName><![CDATA[%s]]></FromUserName>
                    <CreateTime>%s</CreateTime>
                    <MsgType><![CDATA[news]]></MsgType>
                    <ArticleCount>%s</ArticleCount>
                    <Articles>$item_str</Articles>
                    </xml>";

        global $msgcontent;//使用glob访问class外部变量
        $time = time();
        $fromUsername= $msgcontent->FromUserName;
        $toUsername=$msgcontent->ToUserName;
        $contentStr=$resultmsg;
        $resultStr = sprintf($xmlTpl, $fromUsername, $toUsername, $time,$Array_count );
        echo $resultStr;
    }
/*----------以上为纯文本、多图文回复方法----------*//*----------以上为纯文本、多图文回复方法----------*/


    /*  定义音乐回复函数  */
    public function music_response($content)
    {
        $keyword = trim($content->Content);
        if ($keyword=='你好') {
        $this->send_text($keyword)   ;    
        }

    }

    /*  定义语音回复函数  */
    public function voice_response($content)
    {
        $content->Content = mb_substr($content->Recognition,0,-1,"UTF-8");
        $this->cheak_step($content);      
       
    }

    /*  定义视频回复函数  */
    public function video_response($content)
    {
        $result = '您发送的是视频';
        $this->send_text($result)   ;     

    }
    
    /*  定义图片回复函数  */
    public function img_response($content)
    {
        $keyword = trim($content->MediaId);
        
        $this->send_text($keyword)   ;      
            
        

    }

    
    /*  定义地理位置回复函数  */
    public function location_response($content)
    {
        $result="您发送的位置为："."\r"."经度:".$content->Location_Y."\r"."纬度:".$content->Location_X."\r"."您的具体位置为：".$content->Label;     
        $this->send_text($result);  
        

    }
    
    /*  定义事件回复函数  */
    public function first_response($content)
    {
        $result = "【 欢迎 】\r\r看，又一个奇怪的人关注了我！\r试试输入下面的关键字看看\r\r[菜单  翻译  天气  快递]\rPS:也可以直接语音操作哦";
        $this->send_text($result);
    }
    
    /*  定义短视频回复函数  */
    public function shortvideo_response($content)
    {
        $keyword = trim($content->Content);
        if ($keyword=='你好') {
        $this->send_text($keyword)   ;      
            
        }

    }
    
    /*  定义未知类型消息回复函数  */
    public function unknown_response($content)
    {
        $keyword = trim($content->Content);
        if ($keyword=='你好') {
        $this->send_text($keyword)   ;      
            
        }

    }
    /*  进行文本回复函数之前先进行判断，确定用户位置以保持前后文连贯  */
    function cheak_step($content)
    {
        $mem = new Memcached ();
        $keyword = trim($content->Content);
       
        if ($keyword == "退出") {
            $mem->set($content->FromUserName."step","0");
            $return_str = "您已退出到主菜单。输入下面的这些字试试☺：\r\r● 翻译   ● 天气   ● 快递\rPS:也可以直接语音操作哦";
            $this->send_text($return_str);
        }else{
            $step = $mem->get($content->FromUserName."step");
            $last_result = $mem->getResultCode();
            if ($last_result == "16") {//"16"为memcache错误代码，也可写作MEMCACHED_NOTFOUND，意为不存在此文件
            $mem->set($content->FromUserName."step","0");
            $this->text_response($content);
            }else{
                if ($step == "0") {
                    $this->text_response($content);
                }elseif ($step == "translate") {
                    $this->translate($keyword);
                }elseif ($step == "weather") {
                    $this->get_weather($keyword);
                }elseif ($step == "game") {
                    $this->play_game($content);
                }elseif ($step == "express") {
                    $this->express($content);
                }elseif ($step == "message") {
                    if ($content->FromUserName == "oPtNJwkWcntzR8ZVLJp4HI9sxsoU") {
                        $this->get_message($content);
                    }else{
                        $this->write_message($content);
                    }
                }
            }
        }  
        $mem->close();
    }
    /*====================================================================================================================*\
    |*  定义文本回复函数  *//*  定义文本回复函数  *//*  定义文本回复函数  *//*  定义文本回复函数  *//*  定义文本回复函数  *|
    |*  定义文本回复函数  *//*  定义文本回复函数  *//*  定义文本回复函数  *//*  定义文本回复函数  *//*  定义文本回复函数  *|
    \*====================================================================================================================*/
    public function text_response($content)
    {
        $mem = new Memcached ();
        $last_step = $mem->get($content->FromUserName."step");
        $keyword = trim($content->Content);
        if (strstr($keyword, "天气")) {                                   //--获取天气
            if ($last_step == "0") {
                $mem->set($content->FromUserName."step","weather",time()+5*60);//设置memcached失效时间
                $result = "您已进入天气查询模式，请直接输入需要查询的城市名！\r\r输入【退出】即可退出天气查询模式\rPS:也可以直接语音操作哦";
                $this->send_text($result);
            }   
        }elseif ($keyword == "！！" or $keyword == "!!") {                //--进入管理者模式
            if ($content->FromUserName == "oPtNJwkWcntzR8ZVLJp4HI9sxsoU") {
                $now_time = date("Y-m-d H:i:s",time());
                $result = '【 管理员您好！ 】'."\r".'您的微信名为：'.$content->FromUserName."\r".'您要发送给：'.$content->ToUserName."\r\r".'消息创建时间为：'.$now_time;
                $this->send_text($result);
            }else{
                $result = '您怎么知道这个秘密通道的？不过您不是管理员，无法查看后台哦。'  ;
                $this->send_text($result);
            }
        }elseif (strstr($keyword,"翻译")) {                                    //--获取翻译
            
            if ($last_step == "0") {
                $mem->set($content->FromUserName."step","translate",time()+5*60);
                $result = "您已进入翻译模式，接下来的每一句话都会被翻译哦！\r\r输入【退出】即可退出翻译模式\rPS:也可以直接语音操作哦";
                $this->send_text($result);
            }
        
        }elseif ($keyword == "谁是卧底") {
            if ($last_step == "0") {
                $mem->set($content->FromUserName."step","game",time()+5*60);
                $result = "您已进入谁是卧底游戏模式！\r\r输入【退出】即可退出游戏模式\rPS:也可以直接语音操作哦";
                $this->send_text($result);
            }
            
        }elseif ($keyword == "菜单"||$keyword == "目录") {

            $result = "【菜单/目录】\r\r输入☞ 翻译 ☜ 即可进行翻译\r输入☞ 天气 ☜ 即可查询天气\r输入☞ 快递 ☜ 即可查询快递\r输入☞ 退出 ☜ 即可退出以上功能\r\r输入其他字符即可开始聊天 ☺\rPS:也可以直接语音操作哦";
            $this->send_text($result);

        }elseif (strstr($keyword,"快递")) {

            if ($last_step == "0") {
                $mem->set($content->FromUserName."step","express",time()+5*60);
                $result = "您已进入快递查询模式，请输入您的快递单号查询！\r\r输入【退出】即可退出快递查询模式\rPS:也可以直接语音操作哦";
                $this->send_text($result);
            }
        }elseif ($keyword == "留言") {
            if ($content->FromUserName == "oPtNJwkWcntzR8ZVLJp4HI9sxsoU") {
                $mem->set($content->FromUserName."step","message",time()+5*60);
                $result = "☺ 管理员您好 ☺\r\r留言数：15\r请输入序号来查看吧！\r\r输入【退出】即可退出留言模式\rPS:也可以直接语音操作哦";
            }else{
                $mem->set($content->FromUserName."step","message",time()+60*60);
                $result = "您已进入留言模式，有什么好的建议或者悄悄话就对我说吧☺\r\r输入【退出】即可退出留言模式\rPS:也可以直接语音操作哦";  
            }  
            $this->send_text($result);
        }elseif (strstr($keyword,"test")) {
            $this->test_version($content);
            
        }else{
            if (preg_match("/[\x7f-\xff]/", $keyword) or is_numeric($keyword)) {
                $this->chatrobot($keyword);
            }else{
                $this->send_text($keyword);
            }
        }
        $mem->close();

    }
    /*====================================================================================================================*\
    |*****************************************以下为纯文本分析、回复方法。功能函数*****************************************|
    |现已实现功能：聊天机器人，翻译，天气
    \*====================================================================================================================*/
    /*---获取天气代码---*/
    function get_weather($weatherip)
    {
        include ("weatherIcon.php");
        $mem = new Memcached ();
        $mem->set($content->FromUserName."step","weather",time()+5*60);
        $get_url= "https://free-api.heweather.com/v5/forecast?city=".$weatherip."&key=150bd18244a2464193a8976627cea290";
        $return_str =json_decode(file_get_contents($get_url));
        $status = $return_str->HeWeather5[0]->status;
        $weather_time = $return_str->HeWeather5[0]->basic->update->loc;
        $iconCode = array($return_str->HeWeather5[0]->daily_forecast[0]->cond->code_d,$return_str->HeWeather5[0]->daily_forecast[1]->cond->code_d,$return_str->HeWeather5[0]->daily_forecast[2]->cond->code_d);
        if ($status == 'ok') {//查询成功，返回天气
            $content = array();
            $content[0] = array('Title' => '【 '.$weatherip."】最近三天天气一览表\r  (".$weather_time.')',
                    'Description'=>'',
                    'PicUrl'=>'',
                    'Url'=>'');
            $content[1] = array('Title' =>  "[今天天气]\r今天白天： ".$return_str->HeWeather5[0]->daily_forecast[0]->cond->txt_d."      今天夜间： ".$return_str->HeWeather5[0]->daily_forecast[0]->cond->txt_n."\r最高温度： ".$return_str->HeWeather5[0]->daily_forecast[0]->tmp ->max."℃". "      最低温度:".$return_str->HeWeather5[0]->daily_forecast[0]->tmp ->min."℃\r降水概率： ".$return_str->HeWeather5[0]->daily_forecast[0]->pop."      能见度： ".$return_str->HeWeather5[0]->daily_forecast[0]->vis."Km\r风向风力： ".$return_str->HeWeather5[0]->daily_forecast[0]->wind->dir.$return_str->HeWeather5[0]->daily_forecast[0]->wind->sc."级",
                    'Description'=>'',
                    'PicUrl'=>$icon[$iconCode[0]],
                    'Url'=>'');
            $content[2] = array('Title' => "[明天天气]\r明天白天： ".$return_str->HeWeather5[0]->daily_forecast[1]->cond->txt_d."      明天夜间： ".$return_str->HeWeather5[0]->daily_forecast[1]->cond->txt_n."\r最高温度： ".$return_str->HeWeather5[0]->daily_forecast[1]->tmp ->max."℃". "      最低温度:".$return_str->HeWeather5[0]->daily_forecast[1]->tmp ->min."℃\r降水概率： ".$return_str->HeWeather5[0]->daily_forecast[1]->pop."      能见度： ".$return_str->HeWeather5[0]->daily_forecast[1]->vis."Km\r风向风力： ".$return_str->HeWeather5[0]->daily_forecast[1]->wind->dir.$return_str->HeWeather5[0]->daily_forecast[1]->wind->sc."级",
                    'Description'=>'',
                    'PicUrl'=>$icon[$iconCode[1]],
                    'Url'=>'');
            $content[3] = array('Title' => "[后天天气]\r后天白天： ".$return_str->HeWeather5[0]->daily_forecast[2]->cond->txt_d."      后天夜间： ".$return_str->HeWeather5[0]->daily_forecast[2]->cond->txt_n."\r最高温度： ".$return_str->HeWeather5[0]->daily_forecast[2]->tmp ->max."℃". "      最低温度:".$return_str->HeWeather5[0]->daily_forecast[2]->tmp ->min."℃\r降水概率： ".$return_str->HeWeather5[0]->daily_forecast[2]->pop."      能见度： ".$return_str->HeWeather5[0]->daily_forecast[2]->vis."Km\r风向风力： ".$return_str->HeWeather5[0]->daily_forecast[2]->wind->dir.$return_str->HeWeather5[0]->daily_forecast[2]->wind->sc."级",
                    'Description'=>'',
                    'PicUrl'=>$icon[$iconCode[2]],
                    'Url'=>'');
            $content[4] = array('Title' => "输入【退出】即可退出天气查询模式",
                    'Description'=>'',
                    'PicUrl'=>'',
                    'Url'=>'');
            $this->send_articles($content);
        }else{
        	$mem->set($content->FromUserName."step","weather",time()+5*60);
            $content = "似乎没有查到您输入地址的天气，检查一下是不是输入错误啦~\r\r输入【退出】即可退出天气查询模式\rPS:也可以直接语音操作哦";
            $this->send_text($content);
        }
        //$content = $return_str->HeWeather5[0]->daily_forecast[0]->cond->txt_d;
        //$country = $return_str->HeWeather5[0]->basic->cnty;

        /*$today = array                      //今天天气
        (
         'weather_d' => $return_str->HeWeather5[0]->daily_forecast[0]->cond->txt_d, 
         'weather_n' => $return_str->HeWeather5[0]->daily_forecast[0]->cond->txt_n,
         'tmp_max'   => $return_str->HeWeather5[0]->daily_forecast[0]->tmp ->max,
         'tmp_min'   => $return_str->HeWeather5[0]->daily_forecast[0]->tmp ->min,
         'hum'       => $return_str->HeWeather5[0]->daily_forecast[0]->hum."%",
         'wind'      => $return_str->HeWeather5[0]->daily_forecast[0]->wind->dir . $return_str->HeWeather5[0]->daily_forecast[0]->wind->sc ."级",
         'date'      => $return_str->HeWeather5[0]->daily_forecast[0]->date
        );
        $tomorrow = array                   //明天天气
        (
         'weather_d' => $return_str->HeWeather5[0]->daily_forecast[1]->cond->txt_d, 
         'weather_n' => $return_str->HeWeather5[0]->daily_forecast[1]->cond->txt_n,
         'tmp_max'   => $return_str->HeWeather5[0]->daily_forecast[1]->tmp ->max,
         'tmp_min'   => $return_str->HeWeather5[0]->daily_forecast[1]->tmp ->min,
         'hum'       => $return_str->HeWeather5[0]->daily_forecast[1]->hum."%",
         'wind'      => $return_str->HeWeather5[0]->daily_forecast[1]->wind->dir . $return_str->HeWeather5[0]->daily_forecast[0]->wind->sc ."级",
         'date'      => $return_str->HeWeather5[0]->daily_forecast[1]->date
        );
        $after_tomorrow = array             //后天天气
        (
         'weather_d' => $return_str->HeWeather5[0]->daily_forecast[2]->cond->txt_d, 
         'weather_n' => $return_str->HeWeather5[0]->daily_forecast[2]->cond->txt_n,
         'tmp_max'   => $return_str->HeWeather5[0]->daily_forecast[2]->tmp ->max,
         'tmp_min'   => $return_str->HeWeather5[0]->daily_forecast[2]->tmp ->min,
         'hum'       => $return_str->HeWeather5[0]->daily_forecast[2]->hum."%",
         'wind'      => $return_str->HeWeather5[0]->daily_forecast[2]->wind->dir . $return_str->HeWeather5[0]->daily_forecast[0]->wind->sc ."级" ,
         'date'      => $return_str->HeWeather5[0]->daily_forecast[2]->date

        );
        if ($today[weather_d] == "") {
            $content = "【提示】\r未查询到您输入位置的天气，请确认是否输入正确哦！直接输入您需要查询的位置就可以啦！";
        }else{
        //$content = $return_str;

        $content = "【 $weatherip 近3日天气状况】\r\r[$today[date]]\r白天：$today[weather_d]\r夜间：$today[weather_n]\r最高气温：$today[tmp_max]\r最低气温:$today[tmp_min]\r空气湿度：$today[hum]\r风向风速：$today[wind]\r\r[$tomorrow[date]]\r白天：$tomorrow[weather_d]\r夜间：$tomorrow[weather_n]\r最高气温：$tomorrow[tmp_max]\r最低气温:$tomorrow[tmp_min]\r空气湿度：$tomorrow[hum]\r风向风速：$tomorrow[wind]\r\r[$after_tomorrow[date]]\r白天：$after_tomorrow[weather_d]\r夜间：$after_tomorrow[weather_n]\r最高气温：$after_tomorrow[tmp_max]\r最低气温:$after_tomorrow[tmp_min]\r空气湿度：$after_tomorrow[hum]\r风向风速：$after_tomorrow[wind]\r\r";
        }
        $content = $content."\r[如需退出查询天气模式，请输入“退出”]";//提示用户如何退出*/
        $mem->close();
    }
    /*---聊天机器人代码---*/
    function chatrobot($keyword)
    {
        $content_str = urlencode($keyword);
        $get_url = "http://www.simsimi.com/getRealtimeReq?uuid=ryfExPxsxppvMpXHBiWxArMjDk3AAvxP3DlM9cdSvow&lc=zh&ft=1&reqText=".$content_str."&status=W";
        $return_str = file_get_contents($get_url);
        if (strstr($return_str ,"404")) {
            $content = "我现在还不够聪明，没有理解您的意思哦。请换句话试试吧 ☺\r\rPS:也可以直接语音操作哦";
            unset ($return_str);
        }else{
        $return_str = json_decode($return_str);
        $content = $return_str->respSentence;
        }
        $this->send_text($content);
    }

    /*---获取翻译代码---*/
    function translate($keyword)
    {
        $mem = new Memcached ();
        $mem->set($content->FromUserName."step","translate",time()+5*60);
        $keyword = urlencode($keyword);
        $get_url = "http://fanyi.youdao.com/openapi.do?keyfrom=yigong5gezi&key=1305552591&type=data&doctype=json&version=1.1&q=".$keyword;
        $return_str = json_decode(file_get_contents($get_url));
        $content ="译文： ". $return_str->translation[0]."\r\r输入【退出】即可退出翻译模式\rPS:也可以直接语音操作哦";//提示用户如何退出
        $this->send_text($content);
        $mem->close();
    }
    /*---谁是卧底游戏代码---*/
    function play_game($content)
    {
        


    }

    /*---快递查询代码---*/
    function express($content)
    {
        include ("snoopy.php");
        $snoopy = new snoopy();
        $mem = new Memcached ();
        $mem->set($content->FromUserName."step","express",time()+5*60);//调用函数是重新计时，防止使用过程中memcached失效
        $bucket = 'express';
    	$user_path = '/'.$content->FromUserName.'/express.txt';
        $keyword = trim($content->Content);
        //$keyword = "213786468638";
        if (is_dir($bucket.$user_path)) {
        	# code...
        }
        $arrayName = array('text' => $keyword );
        $submit_url= "http://www.kuaidi100.com/autonumber/autoComNum?text=$keyword";
        $snoopy->submit($submit_url,$arrayName);//【查询快递公司名】
        $content_submit = json_decode($snoopy -> results); //$this->results用于返回Snoopy结果，返回的json一定要解码！！！！！！！
        $express_comCode = $content_submit->auto[0]->comCode; 
        $get_url = "http://www.kuaidi100.com/query?type=$express_comCode&postid=$keyword";
        $snoopy ->fetch($get_url);
        $content_get = json_decode($snoopy->results);
        $message = $content_get->message;//查看是否存在单号
        if ($message == "ok") {
        	$s = new SaeStorage();
        	$bucket = 'express';
        	$user_path = '/'.$content->FromUserName.'/express.txt';

            $count =  count($content_get->data);
            for ( $i=0 ;$i < $count ;$i++) { 
                if ($i == 0) {
                    $content = "● ".$content_get->data[$i]->time." : ".$content_get->data[$i]->context;
                }else{
                    $content = "● ".$content_get->data[$i]->time." : ".$content_get->data[$i]->context."\r".$content;
                }
            }
            $article = array
            (
                '0'=>array('Title' => '查看【'.$keyword.'】的快递信息',
                    'Description'=>$content,
                    'PicUrl'=>'',
                    'Url'=>'')
            );
            $this->send_articles($article);

        }else{
            if ($message == "") {
            	$mem->set($content->FromUserName."step","express",time()+5*60);
                $content = "我好像没有查到您的快递，请输入正确的快递单号哦~\r\r输入【退出】即可退出快递查询模式\rPS:也可以直接语音操作哦";
                $this->send_text($content);
            }else{
            	$mem->set($content->FromUserName."step","express",time()+5*60);
                $content = "我好像没有查到您的快递单号  😔 \r 错误原因： $message \r\r输入【退出】即可退出快递查询模式\rPS:也可以直接语音操作哦";
                $this->send_text($content);
            }
        }
        $mem->close();
    }
    /*---游客写留言代码---*/
    function write_message($content)
    {
        $mem = new Memcached ();
        $s = new SaeStorage();
        $mem->set($content->FromUserName."step","express",time()+5*60);
        $keyword = trim($content->Content);
        $bucket = "message";
        $user_path = '/'.$content->FromUserName;
        $www=$s->listBuckets($bucket);
        $this->send_text($www[0]);
        if (file_exists($bucket.$user_path)) {
        	if ($open = opendir($bucket.$user_path)) {
        		while (($read = readdir($open)) !== false) {
        			$messagenum++;
        		}
        	}
        	$this->send_text($messagenum);
            //$message_path = '/'. now().'.txt';
            //$s->write($bucket,$user_path.$message_path,$keyword);
        }else{
            $content = $bucket.$user_path;
            $this->send_text($content);
        }
        $s->close();
        $mem->close();
    }
    /*---管理员读取留言代码---*/
    function get_message($value='')
    {
    	# code...
    }
    /*---功能测试代码---*/

    function test_version($content)
    {
        /*include ("snoopy.php");
        $snoopy = new snoopy();
        $post_str = array ('info'=>'你是谁啊',
            'userid'=>'',
            '_xsrf'=>'');
        $post_url = "http://www.tuling123.com/api/product_exper/chat.jhtml";
        $snoopy -> submit($post_url,$post_str);
        $content = $snoopy->results;
        //$this->send_text($content);
        $s = new SaeStorage();
        $a = 'test';
        $b = '/test/a.text';
        $s->write($a,$b,$content);*/
        /*include ('snoopy.php');
        $snoopy = new snoopy();
        $keyword = urldecode(str_replace("test","",trim($content->Content)));
        $content = array('source'=>$keyword,'param1'=>'0','param2'=>'1') ;
        $url = "http://www.pullword.com/process.php";
        $snoopy->submit($url,$content);
        $results = trim(substr(strstr($snoopy->results,"UTF-8"),5));
        $explode_str = array();
        $explode_str = explode(':',$results);
        $explode_num = count($explode_str);
        if ($explode_num > 2) {
        	for ($i=1; $i < $explode_num-1; $i++) { 
        		preg_match('[\u4e00-\u9fa5]',$explode_str[$i],$word[$i-1]);
        		$chance[$i-1] = str_replace($word[$i],'',$explode_str[$i]);
        	}
        	$word[0] = $explode_str[0];
        	$chance[$explode_num-1] = $explode_str[$explode_num-1];
        }
        $this->send_text($word[1]);*/
        include ('snoopy.php');
        $snoopy = new snoopy();
        $url = 'http://www.tuling123.com/openapi/api';
        $keyword = urldecode(str_replace("test","",trim($content->Content)));
        $post_str = json_encode(array('key' =>'839686e67b8247d88652d52f339d2052' , 'info'=>$keyword,'userid'=>$content->FromUserName));
        $snoopy->submit($url,$post_str);
        $result = $snoopy->results;
        $this->send_text($result);
    }

}


?>